package com.example.news.controller;

import com.example.news.pojo.Book;
import com.example.news.pojo.PageResult;
import com.example.news.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;
import java.util.List;

@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    //查询全部图书信息
    @RequestMapping("/all_books")
    public String getAllBooks(Integer pageNo, Integer publisherId, Model model){
        pageNo = pageNo == null?1 : pageNo;
        publisherId = publisherId == null?0 : publisherId;
        PageResult<Book> allBooks = bookService.getAllBooks(pageNo, publisherId);
        model.addAttribute("allBooks",allBooks);
        model.addAttribute("publisherList",bookService.getAllPublisher());
        model.addAttribute("publisherId",publisherId);
        return "all_books";
    }

    //跳转添加页面
    @RequestMapping("/goto_add")
    public String gotoAddBook(Model model){
        //出版社下拉列表
        model.addAttribute("publisherList", bookService.getAllPublisher());
        //图书分类列表
        model.addAttribute("categoryList", bookService.getAllCategory());
        return "add_book";
    }

    //添加图书
    @RequestMapping("/add_book")
    public String addBook(Book book, Integer[] categoryId,Model model){
        Integer result = bookService.addBook(book, Arrays.asList(categoryId));
        if(result > 0){
            model.addAttribute("message", "添加成功");
        } else {
            model.addAttribute("message", "添加失败");
        }
        return "redirect:all_books";
    }

    //跳转更新页面
    @RequestMapping("/goto_update")
    public String gotoUpdate(Integer bookId, Model model){
        //数据回显
        model.addAttribute("book", bookService.findBookById(bookId));
        model.addAttribute("publisherList", bookService.getAllPublisher());
        model.addAttribute("categoryList", bookService.getAllCategory());
        return "set_book";
    }

    //更新图书信息
    @RequestMapping("/update_book")
    @Transactional
    public String updateBook(Book book, Integer bookId, Integer[] categoryId){
        System.out.println("进入修改方法...");
        System.out.println(book.toString());
        bookService.updateBookInfo(book);
        bookService.delBookRelationInfo(bookId);
        bookService.addBookRelationInfo(bookId, Arrays.asList(categoryId));
        return "redirect:all_books";
    }
}
